package com.markix;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import java.security.KeyPair;
import java.util.Date;

/**
 * @author markix
 * @date 2022/8/27 21:55
 */
public class ClientJwtTest {

    public static void main(String[] args) throws JOSEException {
        String clientId = "client4";
        String clientSecret = "01234567890123456789012345678912";

        // 至少以下四项信息
        JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                // 主体：固定clientId
                .subject(clientId)
                // 发行者：固定clientId
                .issuer(clientId)
                // 授权中心的地址
                .audience("http://localhost:9000")
                // 过期时间 24h
                .expirationTime(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                .build();

        String jwt = rsaSign(claimsSet);
        System.out.println(jwt);
        // eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJjbGllbnQ0Iiwic3ViIjoiY2xpZW50NCIsImF1ZCI6Imh0dHA6XC9cL2xvY2FsaG9zdDo5MDAwIiwiZXhwIjoxNjY0NTAyNTQ0fQ.dcgZNb_pSRGmA36SoU2EeI1ZcwYjSfLNvs_xy14m3m9kU6yA4Q2-mny8CqXwPW9JVPd0UlExV6lizJsjpf2WUBIAbwjnifAwX7bGPp7rlwAgQQm5CCClE_G5KpRWAtsjeLH6hu-AYP5vkGg_5ErhMR23YvEQBf41N_c8UDa9kn6Ti0PH86ZjFBssZmlxaKXQXu6gmQiwEE1JpDo-hWvro62TEyYS0vCcMJGdJE5CMQ-sPweKOnAC1D3mdbFqeop_LCtfpshbbirbFiUKXK3C4hR9TbHiaFuW4myt_yx2RdPOGUs5IC2l-QDMxwbE8s4PAx-5uhHNvA_nQCtMbUkmOg
    }


    /**
     * 使用 RSA 算法加签生成jwt
     */
    private static String rsaSign(JWTClaimsSet claimsSet) throws JOSEException {
        KeyPair keyPair = JwksController.loadRsaKey();
        RSASSASigner signer = new RSASSASigner(keyPair.getPrivate());

        SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
        signedJWT.sign(signer);
        String token = signedJWT.serialize();
        return token;
    }

}
